package com.ruoyi.mall.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.service.IMallTimeOrderService;

/**
 * 抢购订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-01
 */
@Service
public class MallTimeOrderServiceImpl implements IMallTimeOrderService
{
    @Autowired
    private MallTimeOrderMapper mallTimeOrderMapper;
    @Autowired
    private MallTimeGoodsMapper mallTimeGoodsMapper;
    @Autowired
    private MallMemberUserMapper mallMemberUserMapper;
    @Autowired
    private MallDistributionConfigMapper mallDistributionConfigMapper;
    @Autowired
    private MallTimeWithdrawMapper mallTimeWithdrawMapper;
    @Autowired
    private MallShopExpressCodeMapper mallShopExpressCodeMapper;

    /**
     * 查询抢购订单
     *
     * @param id 抢购订单主键
     * @return 抢购订单
     */
    @Override
    public MallTimeOrder selectMallTimeOrderById(Long id)
    {
        return mallTimeOrderMapper.selectMallTimeOrderById(id);
    }

    /**
     * 查询抢购订单列表
     *
     * @param mallTimeOrder 抢购订单
     * @return 抢购订单
     */
    @Override
    public List<MallTimeOrder> selectMallTimeOrderList(MallTimeOrder mallTimeOrder)
    {
        return mallTimeOrderMapper.selectMallTimeOrderList(mallTimeOrder);
    }

    /**
     * 新增抢购订单
     *
     * @param mallTimeOrder 抢购订单
     * @return 结果
     */
    @Override
    public int insertMallTimeOrder(MallTimeOrder mallTimeOrder)
    {
        mallTimeOrder.setCreateTime(DateUtils.getNowDate());
        return mallTimeOrderMapper.insertMallTimeOrder(mallTimeOrder);
    }

    /**
     * 修改抢购订单
     *
     * @param mallTimeOrder 抢购订单
     * @return 结果
     */
    @Override
    public int updateMallTimeOrder(MallTimeOrder mallTimeOrder)
    {
        mallTimeOrder.setUpdateTime(DateUtils.getNowDate());
        if (mallTimeOrder.getExpressId() != null) {
            MallShopExpressCode expressCodeById = mallShopExpressCodeMapper.selectMallShopExpressCodeById(mallTimeOrder.getExpressId());
            if (expressCodeById != null) {
                mallTimeOrder.setExpressName(expressCodeById.getName());
                mallTimeOrder.setExpressTime(new Date());
                mallTimeOrder.setStatus(5);
            }
        }
        return mallTimeOrderMapper.updateMallTimeOrder(mallTimeOrder);
    }

    /**
     * 批量删除抢购订单
     *
     * @param ids 需要删除的抢购订单主键
     * @return 结果
     */
    @Override
    public int deleteMallTimeOrderByIds(Long[] ids)
    {
        return mallTimeOrderMapper.deleteMallTimeOrderByIds(ids);
    }

    /**
     * 删除抢购订单信息
     *
     * @param id 抢购订单主键
     * @return 结果
     */
    @Override
    public int deleteMallTimeOrderById(Long id)
    {
        return mallTimeOrderMapper.deleteMallTimeOrderById(id);
    }

    /**
     * 用户今日抢购单数量
     * @param userId 用户ID
     */
    @Override
    public int timeOrderNumTodayByUserId(Long userId) {
        return mallTimeOrderMapper.timeOrderNumTodayByUserId(userId);
    }

    /**
     * 取消订单
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @Override
    public int cancelOrderByUserIdOrderId(Long userId, Long orderId) {
        MallTimeOrder timeOrder = mallTimeOrderMapper.selectMallTimeOrderById(orderId);
        if (timeOrder == null || timeOrder.getStatus() != 1) {
            return 0;
        }
        // 取消订单
        MallTimeOrder order = new MallTimeOrder();
        order.setId(timeOrder.getId());
        order.setCancelTime(new Date());
        order.setStatus(7);
        order.setSellerStatus(7);
        mallTimeOrderMapper.updateMallTimeOrder(order);
        // 商品改为发布
        MallTimeGoods goods = new MallTimeGoods();
        goods.setId(timeOrder.getGoodsId());
        goods.setIsPublish(1);
        mallTimeGoodsMapper.updateMallTimeGoods(goods);
        return 1;
    }

    /**
     * 确认付款
     * @param userId 用户ID
     * @param orderId 订单ID
     */
    @Override
    public int confirmThePayment(Long userId, Long orderId) {
        // 改订单状态
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(userId);// 卖家信息
        MallTimeOrder mallTimeOrder = mallTimeOrderMapper.selectMallTimeOrderById(orderId);
        if (mallMemberUser !=null && mallTimeOrder != null) {
            MallTimeOrder timeOrder = new MallTimeOrder();
            timeOrder.setId(mallTimeOrder.getId());
            timeOrder.setStatus(3);
            timeOrder.setSellerStatus(3);
            timeOrder.setIsPay(1);
            timeOrder.setSellerReviewTime(new Date());
            mallTimeOrderMapper.updateMallTimeOrder(timeOrder);

            // 改商品归属人
            MallTimeGoods mallTimeGoods = mallTimeGoodsMapper.selectMallTimeGoodsById(mallTimeOrder.getGoodsId());
            MallMemberUser buyersUser = mallMemberUserMapper.selectMallMemberUserById(mallTimeOrder.getBuyersUserId());// 买家信息

            if (mallTimeGoods != null && buyersUser != null) {
                MallTimeGoods timeGoods = new MallTimeGoods();
                timeGoods.setId(mallTimeGoods.getId());
                timeGoods.setPid(mallTimeGoods.getUserId());
                timeGoods.setUserId(buyersUser.getId());
                timeGoods.setUserName(buyersUser.getName()+"--"+buyersUser.getPhone());
                timeGoods.setIsPublish(0);
                mallTimeGoodsMapper.updateMallTimeGoods(timeGoods);

                // 分销
                if (buyersUser.getIntroUser() != 0) {
                    // 上级
                    MallMemberUser introUserOne = mallMemberUserMapper.selectMallMemberUserById(buyersUser.getIntroUser());
                    if (introUserOne != null) {
                        MallDistributionConfig distributionConfig = mallDistributionConfigMapper.findMallDistributionConfig();
                        // 如果比例为0.00，则使用固定规则，如果都为0.00则无分销佣金
                        if (!distributionConfig.getFirstPercent().equals(new BigDecimal("0.00")) ||
                                !distributionConfig.getFirstCommission().equals(new BigDecimal("0.00"))) {
                            MallTimeWithdraw timeWithdrawOne = new MallTimeWithdraw();
                            timeWithdrawOne.setWithdrawId("RC"+ UUID.randomUUID());
                            timeWithdrawOne.setResId(mallTimeOrder.getOrderNumber());
                            timeWithdrawOne.setUserId(introUserOne.getId());
                            timeWithdrawOne.setUserName(introUserOne.getName());
                            if (distributionConfig.getFirstPercent().equals(new BigDecimal("0.00"))){
                                // 一级分销提成 固定金额
                                timeWithdrawOne.setMoney(distributionConfig.getFirstCommission());
                                timeWithdrawOne.setActualMoney(distributionConfig.getFirstCommission());
                            } else {
                                // 一级分销 = 商品价*一级分销比例
                                BigDecimal distributionOne = mallTimeGoods.getPrice().multiply(distributionConfig.getFirstPercent()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
                                timeWithdrawOne.setMoney(distributionOne);
                                timeWithdrawOne.setActualMoney(distributionOne);
                            }
                            timeWithdrawOne.setCreateTime(new Date());
                            timeWithdrawOne.setType(0);
                            timeWithdrawOne.setStatus(0);
                            timeWithdrawOne.setIsArrival(2);
                            mallTimeWithdrawMapper.insertMallTimeWithdraw(timeWithdrawOne);
                        }
                        // 上上级
                        MallMemberUser introUserTwo = mallMemberUserMapper.selectMallMemberUserById(introUserOne.getIntroUser());
                        if (introUserTwo != null) {
                            // 如果比例为0.00，则使用固定规则，如果都为0.00则无分销佣金
                            if (!distributionConfig.getSecondPercent().equals(new BigDecimal("0.00")) ||
                                    !distributionConfig.getSecondCommission().equals(new BigDecimal("0.00"))) {
                                MallTimeWithdraw timeWithdrawTwo = new MallTimeWithdraw();
                                timeWithdrawTwo.setWithdrawId("RC"+ UUID.randomUUID());
                                timeWithdrawTwo.setResId(mallTimeOrder.getOrderNumber());
                                timeWithdrawTwo.setUserId(introUserTwo.getId());
                                timeWithdrawTwo.setUserName(introUserTwo.getName());
                                if (distributionConfig.getFirstPercent().equals(new BigDecimal("0.00"))){
                                    // 二级分销提成 固定金额
                                    timeWithdrawTwo.setMoney(distributionConfig.getSecondCommission());
                                    timeWithdrawTwo.setActualMoney(distributionConfig.getSecondCommission());
                                } else {
                                    // 二级分销 = 商品价*二级分销比例
                                    BigDecimal distributionTwo = mallTimeGoods.getPrice().multiply(distributionConfig.getSecondPercent()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
                                    timeWithdrawTwo.setMoney(distributionTwo);
                                    timeWithdrawTwo.setActualMoney(distributionTwo);
                                }
                                timeWithdrawTwo.setCreateTime(new Date());
                                timeWithdrawTwo.setType(0);
                                timeWithdrawTwo.setStatus(0);
                                timeWithdrawTwo.setIsArrival(2);
                                mallTimeWithdrawMapper.insertMallTimeWithdraw(timeWithdrawTwo);
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }

    @Override
    public List<MallTimeOrder> selectMyFansTimeOrderList(Long userId) {
        return mallTimeOrderMapper.selectMyFansTimeOrderList(userId);
    }

    @Override
    public ApiResult confirmReceipt(Long userId, Long orderId) {
        // 用户信息
        MallMemberUser mallMemberUser = mallMemberUserMapper.selectMallMemberUserById(userId);
        // 订单信息
        MallTimeOrder mallTimeOrder = mallTimeOrderMapper.selectMallTimeOrderById(orderId);
        if (mallMemberUser !=null && mallTimeOrder != null) {
            if (mallTimeOrder.getStatus() != 5) {
                return ApiResult.error("订单状态错误");
            }
            // 商品信息
            MallTimeGoods mallTimeGoods = mallTimeGoodsMapper.selectMallTimeGoodsById(mallTimeOrder.getGoodsId());
            if (mallTimeGoods == null) {
                return ApiResult.error("商品错误");
            }
            // 改订单状态
            MallTimeOrder timeOrder = new MallTimeOrder();
            timeOrder.setId(mallTimeOrder.getId());
            timeOrder.setStatus(6);
            timeOrder.setConfirmTime(new Date());
            timeOrder.setReviewTime(new Date());
            mallTimeOrderMapper.updateMallTimeOrder(timeOrder);

            // 改商品
            MallTimeGoods timeGoods = new MallTimeGoods();
            timeGoods.setId(mallTimeGoods.getId());
            timeGoods.setUserId(0L);
            timeGoods.setUserName("平台");
            timeGoods.setIsPublish(0);
            mallTimeGoodsMapper.updateMallTimeGoods(timeGoods);
        }
        return ApiResult.ok("已确认收货");
    }

    /**
     * 今日数据折线图
     */
    @Override
    public Map<String, Object> queryTodayLineChart() {
        return mallTimeOrderMapper.queryTodayLineChart();
    }

    /**
     * 历史数据折线图（流水、消费人数）
     */
    @Override
    public Map<String, Object> queryHistoryLineChart(Map<String, Object> map) {
        return mallTimeOrderMapper.queryHistoryLineChart(map);
    }

    /**
     * 历史数据折线图（营业额、成交单数）
     */
    @Override
    public Map<String, Object> queryHistoryLineChart2(Map<String, Object> map) {
        return mallTimeOrderMapper.queryHistoryLineChart2(map);
    }

    /**
     * 分销商列表查看总流水
     *
     * @param userId：用户ID
     * @return 抢购订单集合
     */
    @Override
    public List<MallTimeOrder> distributorListViewTotalFlow(Long userId) {
        return mallTimeOrderMapper.distributorListViewTotalFlow(userId);
    }

    @Override
    public List<MallTimeOrder> distributorListViewSubordinate(Long userId) {
        return mallTimeOrderMapper.distributorListViewSubordinate(userId);
    }
}
